/*
 * VideoController.java
 * Copyright 2018 Qunhe Tech, all rights reserved.
 * Qunhe PROPRIETARY/CONFIDENTIAL, any form of usage is subject to approval.
 */

package com.bearox.trans.controller;

import com.bearox.trans.data.dto.VideoDto;
import com.bearox.trans.data.vo.VideoVo;
import com.bearox.trans.service.VideoService;
import com.bearox.trans.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Bearox
 */
@RestController
public class VideoController {
    private static final String HAS_MORE = "hasMore";
    private static final String LIST = "list";
    private static final int TWO = 2;

    private final VideoService videoService;

    public VideoController(final VideoService videoService) {
        this.videoService = videoService;
    }

    @GetMapping("/api/video/list")
    public Result getVideoList(@RequestParam(value = "courseid") final long courseId,
            @RequestParam(value = "start", defaultValue = "0") final long start,
            @RequestParam(value = "num", defaultValue = "10") final int num) {
        List<VideoDto> videoDtos = videoService.getVideoListByCourseId(courseId, start, num + 1);
        if (CollectionUtils.isEmpty(videoDtos)) {
            return Result.ok();
        }
        final Map<String, Object> ret = new HashMap<>(TWO);
        ret.put(HAS_MORE, false);
        if (videoDtos.size() > num) {
            ret.put(HAS_MORE, true);
            videoDtos = videoDtos.subList(0, num);
        }
        ret.put(LIST, videoDtos.stream().map(a -> {
            final VideoVo videoVo = new VideoVo();
            BeanUtils.copyProperties(a, videoVo);
            return videoVo;
        }).collect(Collectors.toList()));
        return Result.ok(ret);
    }

    @PostMapping("/api/video/add")
    public Result addVideo(@RequestBody final VideoVo videoVo) {
        if (videoVo == null) {
            return Result.error("Empty video data.");
        }
        final VideoDto videoDto = new VideoDto();
        BeanUtils.copyProperties(videoVo, videoDto);
        return Result.ok(videoService.addVideo(videoDto));
    }
}
